package common;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class BaseServlet
 */
@WebServlet("/BaseServlet")
public abstract class BaseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public abstract String basefun(HttpServletRequest request, HttpServletResponse response) throws IOException;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public BaseServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    public void invalidateSession(HttpSession session) {
    	//清空session信息
    	System.out.println("清空session信息");
		CartShop cartShop=new CartShop(0);
		cartShop.getCarts().clear();
		session.setAttribute("cartShop", cartShop);
		session.setAttribute("ifEmpty",cartShop.ifEmpty());
		session.setAttribute("user", null);
		session.setAttribute("ifLogin", 0);
    }
    
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//处理编码格式
    	//1、设置字符集
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		
		HttpSession session = request.getSession();
		//2、设置网页根路径（工程名）
		session.setAttribute("_ctx", request.getContextPath() + "/");
		
		//1. 获取参数，用来识别用户想请求的方法
        //method是用户在浏览器地址栏中输入的想要调用的方法，是个参数
		String methodName=request.getParameter("method");
		//默认方法为basefun
		if(methodName==null||methodName.equals("")){
    		methodName="basefun";
    	}
		//获取当前对象
        Class c = this.getClass();
        System.out.println(c);
        Method method = null ;
        
        try {
        	//通过反射获取传入的方法名
        	//比如传入login ， 则会调用login方法
			method = c.getMethod(methodName, 
			        HttpServletRequest.class,HttpServletResponse.class);
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        try {
        	//调用之前方法并获取返回值，格式为"r/f：url"
			 String result =(String)method.invoke(this, request,response);
		     //处理返回值， 并进行页面跳转
			 //规则  f:/a.jsp  转发
			 // r:a.jsp  重定向
			if(result!=null){
				 int index = result.indexOf(":");
				 String operate = result.substring(0,index);
				 String path = result.substring(index+1);
				 if(result.contains(":")){
		        	if(operate.equalsIgnoreCase("r")){
		                response.sendRedirect(request.getContextPath()+"/"+path);
		            }else if(operate.equalsIgnoreCase("f")){
		                request.getRequestDispatcher("/WEB-INF/"+path+".jsp").forward(request, response);
		            }
				 }
			}
			
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
